//
//  LYRefresh.m
//  LYRefresh
//
//  Created by boom on 2017/5/3.
//  Copyright © 2017年 boomLi. All rights reserved.
//

#import "LYRefresh.h"

#define BGRefreshViewH 80
#define screenH [UIScreen mainScreen].bounds.size.height
#define screenW [UIScreen mainScreen].bounds.size.width

/**控件的刷新状态*/
typedef enum{
    RefreshStateNormal = 1,//没刷新状态
    RefreshStateRefreshing = 2,//刷新状态
}RefreshState;

@interface LYRefresh()

@property (nonatomic, assign)UIEdgeInsets scrollviewInsets;

@property (nonatomic, assign)CGFloat lastOffset;

@property (nonatomic, assign)RefreshState state;

@property (assign, nonatomic)BOOL refreshing;

@property (assign, nonatomic)float iconScale;

@end

@implementation LYRefresh

/**
 刷新完毕隐藏
 */
-(void)hide{
    UIEdgeInsets inset = _scrollView.contentInset;
    inset.top = _scrollviewInsets.top;
    [UIView animateWithDuration:0.3 animations:^{
        _scrollView.contentInset = inset;
    }];
    
    [self setState:RefreshStateNormal];
    [_header.iconImageView stopAnimating];
    self.iconScale = 0.0;
    if (self.endBlock) {
        self.endBlock();
    }
}

-(void)free{
    // 移除之前的监听器
    [_scrollView removeObserver:self forKeyPath:@"contentOffset" context:nil];
    _scrollView  = nil;
    [self removeFromSuperview];
}


-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        _refreshing = FALSE;
        _state = RefreshStateNormal;
        _iconScale = 0.0;
        _header = [LYRefreshHeaderView view];
        _header.backgroundColor = [UIColor yellowColor];
        [self addSubview:_header];
        
//        _footer = [LYRefreshFooterView view];
//        _footer.backgroundColor = [UIColor purpleColor];
//        [self addSubview:_footer];
        
    }
    return self;
}

-(void)setScrollView:(UIScrollView *)scrollView{
    _scrollView = scrollView;
    _scrollviewInsets = scrollView.contentInset;
    //为什么顺序不一样高度就不一样
    self.frame = CGRectMake(0, -BGRefreshViewH,screenW,BGRefreshViewH);
    _header.frame = CGRectMake(0, 0, screenW, BGRefreshViewH);
//    _footer.frame = CGRectMake(0, _scrollView.contentSize.height, screenW, BGRefreshViewH);
     NSLog(@"======%@",_header);
    
    [_scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    [_scrollView addSubview:self];
     NSLog(@"======%@",_header);
}

/**设置刷新view的值*/
-(void)setState:(RefreshState)state{
    if (_state == state) return;
    switch (state) {
        case RefreshStateNormal:
            if ([_header.iconImageView isAnimating]) {
                _header.freshDetailTitle.text = @"下拉刷新...";
            }
            break;
        
        case RefreshStateRefreshing:
            _refreshing = TRUE;
            [self startAnimation];
            break;
        default:
            break;
    }
    _state = state;
    
}

/**开始动画*/
-(void)startAnimation{
    if ([_header.iconImageView isAnimating]) {
        return;
    }
    _header.freshDetailTitle.text = @"松手更新...";
    NSMutableArray * imgArr = [NSMutableArray array];
    for (int i = 0; i < 6; i ++) {
        [imgArr addObject:[UIImage imageNamed:[NSString stringWithFormat:@"loading%d",i]]];
    }
    [_header.iconImageView setAnimationImages:imgArr];
    [_header.iconImageView setAnimationRepeatCount:0];
    [_header.iconImageView setAnimationDuration: 6 * 0.2];
    [_header.iconImageView startAnimating];
}

/**
 设置图片大小
 */
-(void)setIconScale:(float)iconScale{
    _iconScale = iconScale;
    if (![_header.iconImageView isAnimating]) {
        [UIView animateWithDuration:0.1 animations:^{
            [_header.iconImageView setTransform:CGAffineTransformMakeScale(iconScale,iconScale)];
        }];
    }
}


//开始刷新
-(void)beginRefresh{
    //1.增加滚动区域
    UIEdgeInsets inset = _scrollView.contentInset;
    inset.top = _scrollviewInsets.top + BGRefreshViewH;
    _scrollView.contentInset = inset;
    
    //2.设置滚动位置
    _scrollView.contentOffset = CGPointMake(0, _scrollviewInsets.top - BGRefreshViewH);
    _header.freshDetailTitle.text = @"更新中...";
    
    if (_isAutoEnd) {
        [self performSelector:@selector(hide) withObject:self afterDelay:(_refreshTime>=0)?_refreshTime:(-_refreshTime)];
    }
    
    NSLog(@"======%@",self);
    
    if (_startBlock) {
        _startBlock();
    }
}

//监听滑动
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ((![@"contentOffset" isEqualToString:keyPath]) || (_scrollView.contentOffset.y>0))return;
    if (!_scrollView.isDragging && (_state==RefreshStateRefreshing)){//松开进入刷新
        if (_refreshing) {
            _refreshing = false;
            [self beginRefresh];//松手则开始刷新
        }
        return;
    }
    
    CGFloat offsetY = _scrollView.contentOffset.y;
    CGFloat validY = _scrollviewInsets.top;
    if (_scrollView.isDragging) {
        CGFloat validOffsetY = validY - BGRefreshViewH;
        if (offsetY > validOffsetY) {
            if ((_lastOffset-_scrollView.contentOffset.y)>0.0) {//向下
                if (self.iconScale < 1) {
                    self.iconScale = sin((((-_scrollView.contentOffset.y))/BGRefreshViewH)*0.5*M_PI);
                    if (self.iconScale >= 0.98) {
                        [self setState:RefreshStateRefreshing];
                    }
                }
            }else{//向上
                self.iconScale = sin((((-_scrollView.contentOffset.y))/BGRefreshViewH)*0.5*M_PI);
                if (self.iconScale>0.0 && self.iconScale <= 0.98) {
                    [self setState:RefreshStateNormal];
                }
            }
        }
    }else{
        [self setState:RefreshStateNormal];
        self.iconScale = 0.0;
    }
    _lastOffset = _scrollView.contentOffset.y;
    // NSLog(@"contentoffset = %f, scale = %f",_scrollview.contentOffset.y,sin((((-_scrollview.contentOffset.y))/BGRefreshViewH)*0.5*M_PI));
}





@end
